<?php


namespace App\Http\Controllers\Internal;


use App\Exceptions\OrderNotFoundException;
use App\Models\Order;
use App\Models\OrderItem;

class OrderController extends Controller
{

    public function getCoursesByUserId()
    {
        $this->validate($this->request, [
            'userId' => 'required|integer'
        ]);
        $userId = $this->request->input('userId');
        $courseIds = OrderItem::ofUserPaid($userId)->pluck('course_id');
        return $this->sendSuccessJson($courseIds);
    }

    /*
     * @api get /internal/orders/timeout 获取超时订单
     * @version 0.0.1
     * @group web
     *
     * @param query int [pageSize] 页数，默认15
     * @param query int [page] 页码，默认1
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     * "total[总数]":9,"items[项]":[{"id[id]":9,"tradeNo[订单号]":"20180706081815449610","status[状态]":10,"paidAmount[实际付款]":"0.00","cover[封面图片]":"","issue[期数]":1}]
     *   }
     * }
     */
    public function getTimeoutOrders()
    {
        $this->validate($this->request, [
            "page" => "integer|min:1",
            "pageSize" => "integer|max:100|min:5"
        ]);
        $page = intval($this->request->input("page", 1));
        $pageSize = intval($this->request->input("pageSize", 15));
        $query = Order::ofTimeoutOrder();
        $items = [];
        $ordersObj = $query->orderBy('id', 'asc')->forPage($page, $pageSize)->get();
        /** @var Order $orderObj */
        foreach ($ordersObj as $orderObj) {
            $items[] = [
                'id' => $orderObj->getId(),
                'userId' => $orderObj->getUserId(),
                'name' => $orderObj->getName(),
                'tradeNo' => $orderObj->getTradeNo(),
                'actualPrice' => $orderObj->getActualAmount(),
                'courseLevels' => $orderObj->items()->pluck('level')->toArray(),
            ];
        }
        return $this->sendSuccessJson($items);
    }

    /*
     * @api post /internal/orders/{orderId}/cancel 取消订单
     * @version 0.0.1
     * @group web
     *
     * @param path int orderId 订单ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *  }
     * }
     */
    public function cancel($orderId)
    {
        /** @var Order $orderObj */
        $orderObj = Order::where('id', $orderId)->first();
        if (!$orderObj) {
            throw new OrderNotFoundException();
        }
        if (!$orderObj->checkCancelStatus()) {
            throw new OrderNotFoundException();
        }
        $orderObj->setStatus(Order::ORDER_STATUS['canceled']);
        $orderObj->save();
        return $this->sendSuccessJson();
    }
}